package top.buluoluo.userservice.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.flywaydb.core.internal.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.buluoluo.commoncore.utils.JwtUtil;
import top.buluoluo.userservice.service.TokenManagerService;
import top.buluoluo.userservice.service.UserService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


//@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TokenManagerService tokenManagerService;

    @Autowired
    private UserService userService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        // 1. 从请求中提取Token
        String token = extractTokenFromRequest(request);
        System.out.println("请求头中的token666是:" + token);

        if (token != null) {
            try {
                // 2. 验证JWT本身是否有效
                if (!jwtUtil.validateToken(token)) {
                    sendErrorResponse(response, "Token无效或已过期");
                    return;
                }
                System.out.println("测试！！！！！！！"+tokenManagerService.isTokenBlacklisted(token));
                // 3. 检查Token是否在黑名单中
                if (tokenManagerService.isTokenBlacklisted(token)) {
                    sendErrorResponse(response, "Token已被拉黑，请重新登录");
                    return;
                }

                // 4. 验证通过，设置认证信息
                setAuthentication(token);

            } catch (Exception e) {
                sendErrorResponse(response, "Token验证失败");
                return;
            }
        }

        // 5. 继续执行过滤器链
        chain.doFilter(request, response);
    }

    private String extractTokenFromRequest(HttpServletRequest request) {
        // 从Header、Cookie等地方提取Token
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    private void setAuthentication(String token) {
        // 从Token中解析用户信息
        Long userId = jwtUtil.getUserIdFromToken(token);
        // 从数据库查询用户角色信息
        List<String> roles = userService.getUserRoles(userId);
        // 创建权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : roles) {
            // Spring Security 要求角色名称以 "ROLE_" 开头
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
        // 创建认证对象
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userId, null, authorities);
        // 设置到SecurityContext中
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\":401,\"message\":\"" + message + "\"}");
    }
}